<template>
  <div class="app-container">
    <el-card :style="{ borderRadius: '5px' }">
      <div class="filter-container">
        <el-input v-model="listQuery.name" placeholder="名称" style="width: 200px; margin-right: 10px; margin-top: 10px"
          @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.nickName" placeholder="昵称" style="width: 200px; margin-right: 10px; margin-top: 10px"
          @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.phone" placeholder="电话" style="width: 200px; margin-right: 10px; margin-top: 10px"
          @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.email" placeholder="邮箱" style="width: 200px; margin-right: 10px; margin-top: 10px"
          @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.inviteCode" placeholder="邀请码"
          style="width: 200px; margin-right: 10px; margin-top: 10px" @keyup.enter.native="handleFilter" />
        <el-select v-model="listQuery.type" style="width: 200px; margin-right: 10px" placeholder="请选择类型" clearable>
          <el-option v-for="item in typeOption" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
        <el-select v-model="listQuery.status" style="width: 200px; margin-right: 10px" placeholder="请选择类型" clearable>
          <el-option v-for="item in statusOption" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
        <el-date-picker v-model="createTimeDateVul" format="yyyy-MM-dd " value-format="yyyy-MM-dd" type="daterange"
          range-separator="至" start-placeholder="创建时间开始" end-placeholder="创建时间结束" style="width: 410px; margin-right: 10px"
          @change="handlecreateTimeDateChange" />

        <el-button v-waves type="primary" style="margin-top: 10px" plain icon="el-icon-search"
          @click="handleFilter">搜索</el-button>
        <el-button type="primary" plain style="margin-top: 10px" icon="el-icon-plus" @click="handleAdd">添加</el-button>
      </div>
    </el-card>
    <el-card :style="{ marginTop: '10px', borderRadius: '5px' }">
      <el-table v-loading.body="!listLoading" :header-row-style="{ height: '70px' }" :header-cell-style="{
        color: '',
        fontSize: '',
        backgroundColor: '#dfe6ec',
      }" :data="list" border fit highlight-current-row style="width: 100%" tooltip-effect="dark">
        <el-table-column label="序号" width="50px" align="center" type="index" show-overflow-tooltip />
        <el-table-column label="名称" min-width="130px" align="center" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>

        <el-table-column label="昵称" min-width="130px" align="center" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.nickName }}</template>
        </el-table-column>

        <el-table-column label="电话" prop="phone" align="center" width="140px" show-overflow-tooltip />

        <el-table-column label="邮箱" prop="email" align="center" width="180px" show-overflow-tooltip />

        <el-table-column prop="avatarUrl" label="头像" min-width="100px" align="center">
          <template slot-scope="{ row }">
            <div style="display: flex; justify-content: center">
              <HzImg :src="row.avatarUrl" cssStyle="height: 80px;width: 80px" />
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="certUrl" label="证书" min-width="100px" align="center">
          <template slot-scope="{ row }">
            <div style="display: flex; justify-content: center">
              <HzImg :src="row.certUrl" cssStyle="height: 80px;width: 80px" />
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="personPhotoUrl" label="个人照片" min-width="100px" align="center">
          <template slot-scope="{ row }">
            <div style="display: flex; justify-content: center">
              <HzImg :src="row.personPhotoUrl" cssStyle="height: 80px;width: 80px" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="提交房源数" min-width="120px" align="center" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.houses }}</template>
        </el-table-column>

        <el-table-column label="邀请码" min-width="100px" align="center" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.inviteCode }}</template>
        </el-table-column>

        <el-table-column label="密码" min-width="120px" align="center" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.password }}</template>
        </el-table-column>

        <el-table-column label="邀请人" prop="inviteUserId" align="center" width="100px" :formatter="inviteUserIdFormatter"
          show-overflow-tooltip />

        <el-table-column label="类型" min-width="80px" align="center" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <span v-if="row.type == '1'">用户</span>
            <span v-if="row.type == '2'">中介</span>
          </template>
        </el-table-column>

        <el-table-column label="类型" min-width="80px" align="center" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <span v-if="row.status == 0">正常</span>
            <span v-if="row.status == 1">被禁用</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" prop="createTime" align="center" width="170px" show-overflow-tooltip />

        <el-table-column label="操作" align="center" width="320px" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain @click="handleUpdate(scope.row)">编辑</el-button>

            <el-button v-if="scope.row.status == 0" size="mini" type="danger" plain
              @click="disable(scope.row)">禁用</el-button>
            <el-button v-if="scope.row.status == 1" size="mini" type="success" plain
              @click="enable(scope.row)">解禁</el-button>
            <el-button size="mini" type="danger" plain @click="handleBank(scope.row)">银行账户</el-button>
            <el-button size="mini" type="warning" plain @click="handleCoupon(scope.row)">优惠券</el-button>
            <!-- <el-button size="mini" type="danger" plain @click="handleDel(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div v-show="listLoading" class="pagination-container">
        <el-pagination :current-page.sync="listQuery.currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="9"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible1" width="800px">
      <el-form ref="dataForm" :rules="rules" :model="commonInfo" label-width="120px">
        <el-form-item label="名称:" prop="name">
          <el-input v-model="commonInfo.name" style="width: 350px" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="昵称:" prop="nickName">
          <el-input v-model="commonInfo.nickName" style="width: 350px" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="电话:" prop="phone">
          <el-input v-model="commonInfo.phone" style="width: 350px" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="commonInfo.email" style="width: 350px" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="头像:" prop="avatarUrl">
          <HzImgUpload :urls.sync="commonInfo.avatarUrl" :btn-name="'请上传头像'" :fileType.sync="avatarUrl" />
        </el-form-item>
        <el-form-item label="证书:" prop="certUrl">
          <HzImgUpload :urls.sync="commonInfo.certUrl" :btn-name="'请上传证书'" :fileType.sync="certUrl" />
        </el-form-item>
        <el-form-item label="个人照片:" prop="personPhotoUrl">
          <HzImgUpload :urls.sync="commonInfo.personPhotoUrl" :btn-name="'请上传个人照片'" :fileType.sync="personPhotoUrl" />
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input v-model="commonInfo.password" style="width: 350px" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="邀请人:" prop="inviteUserId">
          <el-select v-model="commonInfo.inviteUserId" style="width: 350px" placeholder="请选择邀请人" clearable>
            <el-option v-for="item in userAllOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型:" prop="type">
          <el-select v-model="commonInfo.type" style="width: 350px" placeholder="请选择类型" clearable>
            <el-option v-for="item in typeOption" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="cancelData('form')">取 消</el-button>
        <el-button v-if="dialogStatus === 'create'" type="primary" plain @click.native.prevent="createData('form')">确
          定</el-button>
        <el-button v-else type="primary" plain @click.native.prevent="updateData('form')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="银行账号信息" :visible.sync="dialogFormVisible" width="800px">
      <div class="userInfo">
        <ul>
          <li>
            用户名：{{ userInfo.name || '--' }}
          </li>
          <li>银行名称：{{ userInfo.bank_name || '--' }}</li>
          <li>账户名：{{ userInfo.account_name || '--' }}</li>
          <li>卡号：{{ userInfo.account_number || '--' }}</li>
        </ul>
      </div>
    </el-dialog>
    <el-dialog title="发放优惠券" :visible.sync="dialogVisibleCoupon" width="800px">
      <el-form  label-width="120px">
        <el-form-item label="发放金额:">
          <el-input v-model="money" type="number" style="width: 350px" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="优惠券截至日期:">
          <el-date-picker  style="width: 350px" v-model="expire_date"  value-format="yyyy-MM-dd" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div style="display:flex;justify-content: flex-end;align-items: flex-end;">
        <el-button type="primary" plain @click="dialogVisibleCoupon=false">取 消</el-button>
        <el-button  type="primary" plain @click.native.prevent="onCouponSubmit">发 放</el-button>
      </div>
      <el-table v-loading.body="!listLoading" :header-row-style="{ height: '70px' }"
      :data="couponList" highlight-current-row style="width: 100%" tooltip-effect="dark">
        <el-table-column label="序号" width="50px" align="center" type="index" show-overflow-tooltip />
        <el-table-column label="发放金额" prop="money" align="center" width="140px"/>
        <el-table-column label="发放时间" prop="ctime" align="center"/>
        <el-table-column label="截止日期" prop="expire_date" align="center"/>

        <el-table-column label="状态" min-width="130px" align="center" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.state==0?"未使用":"已使用" }}</template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import HzFileUpload from "@/custom/HzFileUpload";
import HzImgUpload from "@/custom/HzImgUpload";
import HzImg from "@/custom/HzImg";
import HzLink from "@/custom/HzLink";
import waves from "@/directive/waves"; // waves directive
import {
  userList,
  saveObj,
  updateObj,
  bankAccount,
  delObj,
  sendCouponToUser,
  checkUserCouponList
} from "@/api/system/user";

import { fetchAllList as fetchAllUserList } from "@/api/system/user";

//importDictOptions

import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
export default {
  name: "Common",
  directives: {
    waves,
  },
  components: {
    HzFileUpload,
    HzImgUpload,
    HzImg,
    HzLink,
  },
  data() {
    return {
      dateFil: [],
      selectGroup: null,
      showExportPanel: false,
      exportType: "",
      commonInfo: {},
      dialogVisibleCoupon: false,
      options: [],
      couponList:[],//历史优惠券列表
      userid: "",
      loading: false,
      dialogFormVisible1: false,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建",
      },
      name: "",
      userInfo: {
        name: "",
        bank_name: "",
        account_name: "",
        account_number: ""
      },
      list: [],
      total: 0,
      importPanel: false,
      importLoading: null,
      listLoading: false,
      exportTitle: "",
      extra: {}, //额外参数(用于格式化)
      booleanOptions: [
        { name: "是", value: true },
        { name: "否", value: false },
      ],

      createTimeDateVul: [],
      createTimeStart: null,
      createTimeEnd: null,

      typeOption: [
        { name: "用户", value: "1" },
        { name: "中介", value: "2" },
      ],
      statusOption: [
        { name: "正常", value: 0 },
        { name: "被禁用", value: 1 },
      ],
      userAllOptions: [],
      money: "",
      expire_date: "",
      groups: [],
      listQuery: {
        needExtra: true,
        currentPage: 1,
        pageSize: 10,
      },
      rules: {},
    };
  },
  created() {
    this.getList();
    //initDictOptions

    this.createUserIdInit();
  },
  activated() { },

  mounted() { },
  methods: {
    createUserIdInit() {
      let param = {};
      param.needExtra = false;
      fetchAllUserList(param).then((response) => {
        this.userAllOptions = response.data;
        console.log('userAllOptions', this.userAllOptions)
      });
    },
    getCoupon() {
      let params = {
        userid:this.userid
      };
      checkUserCouponList(params).then((response) => {
        this.couponList = response.data.list;
      });
    },

    handlecreateTimeDateChange(v) {
      this.createTimeDateVul = v;
      if (this.createTimeDateVul != null) {
        this.listQuery.createTimeStart = this.createTimeDateVul[0];
        this.listQuery.createTimeEnd = this.createTimeDateVul[1];
      } else {
        this.listQuery.createTimeStart = "";
        this.listQuery.createTimeEnd = "";
      }
      this.listQuery.page = 1;
      this.getList();
    },

    inviteUserIdFormatter(row, column) {
      let id = row.inviteUserId;
      if (this.extra) {
        let map = this.extra["inviteUserIdExtra"];
        let obj = map[id];
        if (obj) {
          return obj["name"];
        }
      }
      return "";
    },

    handleAdd() {
      this.commonInfo = {};
      this.dialogFormVisible1 = true;
      this.dialogStatus = "create";
    },
    handleBank(row) {
      this.userid = row.id;
      bankAccount({ userid: this.userid }).then((response) => {
        console.log(response.data)
        this.userInfo = response.data || { name: "" };
        console.log(this.userInfo)
        if (this.userInfo.name) {
          this.dialogFormVisible = true;
        } else {
          this.$message({
            message: "暂无银行账户信息",
            type: "warning",
          });
        }
      });
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.currentPage = val;
      this.getList();
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          saveObj(this.commonInfo).then(() => {
            this.getList();
            this.dialogFormVisible1 = false;
            this.cancelData();
            this.$refs.cascader.handleClear({});
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.commonInfo = { ...row };
      this.dialogStatus = "update";
      this.dialogFormVisible1 = true;
    },
    enable(row) {
      this.commonInfo = { ...row };
      this.commonInfo.status = 0;
      updateObj(this.commonInfo).then(() => {
        this.getList();
        this.$notify({
          title: "成功",
          message: "操作成功",
          type: "success",
          duration: 2000,
        });
      });
    },
    disable(row) {
      this.commonInfo = { ...row };
      this.commonInfo.status = 1;
      updateObj(this.commonInfo).then(() => {
        this.getList();
        this.$notify({
          title: "成功",
          message: "操作成功",
          type: "success",
          duration: 2000,
        });
      });
    },
    updateData() {
      delete this.commonInfo.createTime;
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          updateObj(this.commonInfo).then(() => {
            this.getList();
            this.dialogFormVisible1 = false;
            this.cancelData();
            this.$refs.cascader.handleClear({});
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    cancelData() {
      this.commonInfo = {};
      this.dialogFormVisible1 = false;
      this.$refs["dataForm"].resetFields();
    },
    handleDel(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delObj({ ids: row.id }).then((res) => {
          if (res.statusCode === 8201) {
            this.handleFilter();
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000,
            });
          } else {
            this.$notify({
              title: "失败",
              message: "删除失败",
              type: "success",
              duration: 2000,
            });
          }
        });
      });
    },
    getList() {
      this.listLoading = false;
      userList(this.listQuery).then((response) => {
        this.list = response.data.records;
        this.extra = response.extra;
        this.total = response.data.total;
        this.listLoading = true;
      });
    },
    handleCoupon(row) {
      console.log('优惠券', row)
      this.userid = row.id;
      this.getCoupon()
      this.dialogVisibleCoupon = true;
    },
    onCouponSubmit(){
     
      if(!this.money){
        this.$message.warning('请输入发放金额');
        return;
      }
      if(!this.expire_date){
        this.$message.warning('请输入到期时间');
        return;
      }
      let obj  = {
         userid:this.userid,
         money:this.money,
         expire_date:this.expire_date
      }
      sendCouponToUser(obj).then(() => {
            this.getList();
            this.dialogVisibleCoupon = false;
            this.getCoupon();
            this.$refs.cascader.handleClear({});
            this.$notify({
              title: "成功",
              message: "发放成功",
              type: "success",
              duration: 2000,
            });
          });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
  },
};
</script>
<style lang="scss" scoped>
.userInfo {
  ul {
    li {
      margin: 10px 0;
      list-style: none;
    }
  }
}
</style>
